<template>
  <div>
    <div :class="{setButton:isActive}">
      <el-button type="primary" icon="el-icon-plus"  size="small" @click="handleInsert">添加用户</el-button>
      <el-button
        size="small"
        icon="el-icon-delete-solid"
        type="danger"
        @click="batchDelete"
      >批量删除</el-button>
      <el-button type="primary" icon="el-icon-aim" size="small" @click="getSerachData">搜索</el-button>
      <el-select v-model="value" filterable placeholder="查询类型" size="small" clearable class="setSelection">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>

      <el-input
        prefix-icon="el-icon-search"
        size="small"
        placeholder="请输入查询内容"
        v-model="input"
        :class="{setInput:isActive}"
        clearable
      ></el-input>

      <el-button
        class="setExcelButton"
        type="success"
        icon="el-icon-document"
        size="small"
        @click="exportData"
      >导出表格</el-button>
      <input-excel @getResult="getMyExcelData"></input-excel>
    </div>
    <el-table
      ref="filterTable"
      :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
      style="width: 100%"
      :default-sort="{prop:'userId',order:'descending'}"
      stripe
      @selection-change="selected"
      max-height="1000"
    >
      <el-table-column fixed type="selection" width="55"></el-table-column>
      <el-table-column fixed prop="userName" sortable label="账号" width="100"></el-table-column>
      <el-table-column sortable v-if="false" prop="userId" label="id" width="150"></el-table-column>
      <el-table-column prop="nickName" label="姓名" width="100"></el-table-column>
      <el-table-column
        prop="sex"
        label="性别"
        width="100"
        :filters="[{ text: '男', value: '男' }, { text: '女', value: '女' }]"
        :filter-method="filterSex"
        filter-placement="bottom-end"
      >
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.sex === '男' ? 'primary' : scope.row.sex === '女' ?'success' :'warning'"
            disable-transitions
          >{{scope.row.sex === '男' ? '男' : scope.row.sex === '女' ? '女' : '未选择'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="telephone" label="手机" width="120"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="150"></el-table-column>
      <el-table-column prop="birthday" label="生日" sortable width="120"></el-table-column>
      <el-table-column prop="comment" label="备注" width="120"></el-table-column>
      <el-table-column prop="recordTime" label="记录时间" sortable width="150"></el-table-column>
      <el-table-column prop="updateTime" label="更新时间" sortable width="150"></el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(scope.row)"></el-button>

          <el-button type="danger" icon="el-icon-delete" size="mini" @click="open(scope.row)"></el-button>

          <el-button
            type="warning"
            @click.native.prevent="deleteRow(scope.$index, tableData)"
            icon="el-icon-remove-outline"
            size="mini"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        :current-page="currentPage"
        :page-sizes="[3,6,8,10,20,100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.length"
      ></el-pagination>
    </div>

    <!-- 添加用户信息dialog -->
    <el-dialog title="添加用户信息" :visible.sync="addUserFormVisible" @click="handleInsert">
      <el-form :model="addForm" :rules="rules" ref="rulesForm">
        <el-form-item label="用户账号" :label-width="formLabelWidth" prop="userName">
          <el-input
            v-model="addForm.userName"
            autocomplete="off"
            prefix-icon="el-icon-user-solid"
            :width="formLabelWidth"
            maxlength="32"
            show-word-limit
            resize
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" :label-width="formLabelWidth" prop="nickName">
          <el-input
            v-model="addForm.nickName"
            autocomplete="off"
            prefix-icon="el-icon-s-custom"
            :width="formLabelWidth"
            maxlength="32"
            show-word-limit
            resize
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" :label-width="formLabelWidth" prop="email">
          <el-input
            v-model="addForm.email"
            autocomplete="off"
            prefix-icon="el-icon-message"
            :width="formLabelWidth"
            maxlength="32"
            show-word-limit
            resize
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="用户手机" :label-width="formLabelWidth" prop="telephone">
          <el-input
            v-model="addForm.telephone"
            autocomplete="off"
            prefix-icon="el-icon-mobile-phone"
            :width="formLabelWidth"
            maxlength="11"
            show-word-limit
            resize
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="用户备注" :label-width="formLabelWidth" prop="comment">
          <el-input
            v-model="addForm.comment"
            autocomplete="off"
            prefix-icon="el-icon-s-comment"
            :width="formLabelWidth"
            maxlength="255"
            show-word-limit
            resize
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="用户生日" :label-width="formLabelWidth" prop="birthday">
          <el-date-picker
            v-model="addForm.birthday"
            align="left"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions"
            resize
            class="setDialogDateAndSex"
            style="width:100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="用户性别" :label-width="formLabelWidth" prop="sex">
          <el-select
            icon="el-icon-male"
            v-model="addForm.sex"
            placeholder="请选择用户性别"
            :width="formLabelWidth"
            resize
            class="setDialogDateAndSex"
            clearable
          >
            <el-option icon="el-icon-male" label="男" value="男">
              <i class="el-icon-male">男性</i>
            </el-option>
            <el-option icon="el-icon-female" label="女" value="女">
              <i class="el-icon-female">女性</i>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd('rulesForm')">取 消</el-button>
        <el-button type="primary" @click="onSubmit('rulesForm')">添 加</el-button>
      </template>
    </el-dialog>

    <!-- 修改用户信息dialog -->
    <el-dialog title="用户信息" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="用户账号" :label-width="formLabelWidth">
          <el-input
            v-model="form.userName"
            autocomplete="off"
            prefix-icon="el-icon-user-solid"
            :width="formLabelWidth"
            maxlength="32"
            show-word-limit
            resize
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" :label-width="formLabelWidth">
          <el-input
            v-model="form.nickName"
            autocomplete="off"
            prefix-icon="el-icon-s-custom"
            :width="formLabelWidth"
            maxlength="32"
            show-word-limit
            resize
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" :label-width="formLabelWidth">
          <el-input
            v-model="form.email"
            autocomplete="off"
            prefix-icon="el-icon-message"
            :width="formLabelWidth"
            maxlength="32"
            show-word-limit
            resize
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="用户手机" :label-width="formLabelWidth">
          <el-input
            v-model="form.telephone"
            autocomplete="off"
            prefix-icon="el-icon-mobile-phone"
            :width="formLabelWidth"
            maxlength="11"
            show-word-limit
            resize
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="用户备注" :label-width="formLabelWidth">
          <el-input
            v-model="form.comment"
            autocomplete="off"
            prefix-icon="el-icon-s-comment"
            :width="formLabelWidth"
            maxlength="255"
            show-word-limit
            resize
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="用户生日" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.birthday"
            align="left"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions"
            resize
            clearable
            class="setDialogDateAndSex"
            style="width:100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="用户性别" :label-width="formLabelWidth">
          <el-select
            icon="el-icon-male"
            v-model="form.sex"
            placeholder="请选择用户性别"
            :width="formLabelWidth"
            resize
            clearable
            class="setDialogDateAndSex"
          >
            <el-option icon="el-icon-male" label="男" value="男">
              <i class="el-icon-male">男性</i>
            </el-option>
            <el-option icon="el-icon-female" label="女" value="女">
              <i class="el-icon-female">女性</i>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdate">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { export2Excel } from '../../../common/js/util'
import inputExcel from '../../common/inputExcel'
export default {
  inject: ['reload'],
  components: { inputExcel },
  data () {
    return {
      dialogFormVisible: false,
      formLabelWidth: '120px',
      pageSize: 6,
      currentPage: 1,
      tableData: [],
      selectedCheckBox: [],
      input: '',
      isActive: true,
      addUserFormVisible: false,
      value: '',
      options: [
        {
          value: 'userName',
          label: '用户账号:'
        },
        {
          value: 'nickName',
          label: '用户昵称:'
        },
        {
          value: 'telephone',
          label: '手机号码:'
        },
        {
          value: 'email',
          label: '用户邮箱:'
        }
      ],
      columns: [
        { title: 'ID', key: 'userId' },
        { title: '账号', key: 'userName' },
        { title: '昵称', key: 'nickName' },
        { title: '性别', key: 'sex' },
        { title: '手机号码', key: 'telephone' },
        { title: '生日', key: 'birthday' },
        { title: '邮箱', key: 'email' },
        { title: '创建时间', key: 'recordTime' },
        { title: '更新时间', key: 'updateTime' }
      ],
      rules: {
        userName: [
          { required: true, message: '请输入账号,不能为空', trigger: 'blur' },
          { min: 6, max: 32, message: '长度在 6 到 32 个字符', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '请输入昵称,不能为空', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别,不能为空', trigger: 'blur' }
        ],
        telephone: [
          {
            required: true,
            message: '请输入手机号码,不能为空',
            trigger: 'blur'
          },
          {
            pattern: /^1[3|4|5|7|8][0-9]{9}$/,
            message: '请输入11位正确的手机号码格式',
            trigger: 'blur'
          }
        ],
        birthday: [
          {
            required: true,
            message: '请选择出生日期,不能为空',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱,不能为空', trigger: 'blur' }
        ]
      },
      addForm: {
        userName: '',
        nickName: '',
        sex: '',
        telephone: '',
        birthday: '',
        email: '',
        comment: ''
      },
      form: {
        userId: '',
        userName: '',
        nickName: '',
        sex: '',
        telephone: '',
        birthday: '',
        email: '',
        comment: '',
        recordTime: '',
        updateTime: ''
      },
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [
          {
            text: '今天',
            onClick (picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      }
    }
  },
  created () {
    this.initData()
  },
  methods: {
    getSerachData () {
      if (this.input === '' && this.value !== '') {
        this.$confirm('查询内容不能为空！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } else if (this.value === '' && this.input !== '') {
        this.$confirm('查询类型内容不能空！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      } else if (this.value === '' && this.input === '') {
        this.initData()
      } else {
        this.$axios
          .post('/users/serachs', {
            json: this.value + ',' + this.input
          })
          .then(response => (this.tableData = response.data.data))
          .catch(function (error) {
            // 请求失败处理
            console.log(error)
          })
      }
    },
    getMyExcelData (data) {
      // alert(JSON.stringify(data))
      if (this.addForm != null) {
        this.$axios
          .post('/users/excels', {
            json: data
          })
          .then(response => {
            if (response.data.code === 200) {
              // alert(JSON.stringify(response.data));
              setTimeout(() => {
                // var obj = JSON.parse(JSON.stringify(response.data.data))
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                this.initData()
                this.reload()
              }, 300)
            } else {
              this.$message({
                message: '添加失败',
                type: 'warning'
              })
              this.reload()
            }
          })
          .catch(function (error) {
            // 请求失败处理
            console.log(error)
          })
      }
      console.log(data)
    },
    exportData () {
      // Excel导出数据
      export2Excel(this.columns, this.tableData)
    },
    onSubmit (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleAdd()
          console.log('success submit!!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    formatSex (row, column) {
      // 格式化性别内容
      return row.sex === '男' ? '男' : row.sex === '女' ? '女' : '未选择'
    },
    clearFilter () {
      // 清空拦截器
      this.$refs.filterTable.clearFilter()
    },
    filterSex (value, row) {
      // 筛选用户性别
      return row.sex === value
    },
    selected: function (value) {
      // 复选框获取已经被选择的记录
      this.selectedCheckBox = value
    },
    batchDelete: function () {
      // 获取所有选中行的id组成的字符串，以逗号分隔
      var ids = this.selectedCheckBox.map(item => item.userId).join()

      console.log(ids)
      // 批量删除操作方法
      this.$confirm('此操作将批量删除已选择记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.handleDeleteUsersByIds(ids)

          // this.$message({
          //   type: "success",
          //   message: "删除成功!"
          // });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleDeleteUsersByIds: function (array) {
      // 删除操作方法
      // alert(index.userId);
      this.$axios
        .post('/users/dels', {
          userIds: array
        })
        .then(response => {
          if (response.data.code === 200) {
            setTimeout(() => {
              this.reload()
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.initData()
            }, 300)
          } else {
            this.$message({
              message: '删除失败',
              type: 'error'
            })
          }
        })
        .catch(failResponse => {
          this.$message({
            message: '请求失败',
            type: 'warning'
          })
        })
    },
    handleSizeChange (val) {
      this.currentPage = 1
      this.pageSize = val
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange (val) {
      this.currentPage = val
      console.log(`当前页: ${val}`)
    },
    deleteRow (index, rows) {
      rows.splice(index, 1)
    },
    open (index) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // alert(index.userId);
          this.handleDelete(index.userId)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    handleAdd: function () {
      // 执行添加用户方法
      this.addUserFormVisible = false
      // alert(JSON.stringify(this.form));
      if (this.addForm != null) {
        this.$axios
          .post('/users', {
            json: this.addForm
          })
          .then(response => {
            if (response.data.code === 200) {
              // alert(JSON.stringify(response.data));
              setTimeout(() => {
                // var obj = JSON.parse(JSON.stringify(response.data.data))
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                this.initData()
                this.initInsert()
                // done可以传入一个对象来修改提交的某个字段
                // done({
                //   birthday: this.timeFormat(new Date())
                // })
              }, 300)
            } else {
              this.$message({
                message: '添加失败',
                type: 'warning'
              })
            }
          })
          .catch(function (error) {
            // 请求失败处理
            console.log(error)
          })
      }
    },
    cancelAdd () {
      this.addUserFormVisible = false // 关闭添加dialog
      this.$refs.rulesForm.resetFields() // 重置表单效验
    },
    handleInsert: function () {
      // 打开添加操作dialog方法
      this.addUserFormVisible = true
    },
    initInsert () {
      this.addForm.userName = '' // 重置用户账号
      this.addForm.nickName = '' // 重置用户昵称
      this.addForm.sex = '' // 重置用户性别
      this.addForm.telephone = '' // 重置用户手机
      this.addForm.birthday = '' // 重置用户生日
      this.addForm.email = '' // 重置用户邮箱
      this.addForm.comment = '' // 重置用户备注
    },
    handleEdit: function (rows) {
      // 打开修改操作dialog方法
      this.dialogFormVisible = true // 打开dialog
      this.form.userId = rows.userId // 获取用户ID
      this.form.userName = rows.userName // 获取用户账号
      this.form.nickName = rows.nickName // 获取用户昵称
      this.form.sex = rows.sex // 获取用户性别
      this.form.telephone = rows.telephone // 获取用户手机
      this.form.birthday = rows.birthday // 获取用户生日
      this.form.email = rows.email // 获取用户邮箱
      this.form.comment = rows.comment // 获取用户备注
      this.form.recordTime = rows.recordTime // 获取用户创建时间
      this.form.updateTime = rows.updateTime // 获取用户更新时间

      console.log(rows)
    },
    handleUpdate: function () {
      // 执行更新操作方法
      this.dialogFormVisible = false
      if (this.form != null) {
        this.$axios
          .put('/users', {
            json: this.form
          })
          .then(response => {
            if (response.data.code === 200) {
              setTimeout(() => {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })

                this.initData()
              }, 300)
            } else {
              this.$message({
                message: '修改失败',
                type: 'warning'
              })
            }
          })
          .catch(function (error) {
            // 请求失败处理
            console.log(error)
          })
      }
      // alert(this.form.toString);
    },
    handleDelete: function (index) {
      // 删除操作方法
      // alert(index.userId);
      this.$axios
        .delete('/users/' + index)
        .then(response => {
          if (response.data.code === 200) {
            setTimeout(() => {
              this.$message({
                message: '删除成功',
                type: 'success'
              })
              this.initData()
            }, 300)
          } else {
            this.$message({
              message: '删除失败',
              type: 'error'
            })
          }
        })
        .catch(failResponse => {
          this.$message({
            message: '请求失败',
            type: 'warning'
          })
        })
    },
    initData () {
      // 初始化数据
      this.$axios
        .get('/users')
        .then(response => (this.tableData = response.data.data))
        .catch(function (error) {
          // 请求失败处理
          console.log(error)
        })
    }
  }
}
</script>
<style scoped>
.setInput {
  width: 200px;
}
.setButton {
  text-align: left;
  margin-left: 0%;
  height: 60px;
}
.setSelection {
  width: 100px;
  background-color: dodgerblue;
}
.setExcelButton {
  margin-left: 5%;
}
.setDialogDateAndSex {
  width: 470px;
}
</style>
